package com.hongxun.design.activitys;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.baidu.mapapi.map.offline.MKOLSearchRecord;
import com.baidu.mapapi.map.offline.MKOLUpdateElement;
import com.baidu.mapapi.map.offline.MKOfflineMap;
import com.baidu.mapapi.map.offline.MKOfflineMapListener;
import com.hongxun.design.R;
import com.hongxun.design.bean.CitysBean;
import com.hongxun.design.fragments.BaseFragment;
import com.hongxun.design.fragments.CitysFragment;
import com.hongxun.design.fragments.DownloadmanagementFragment;
import com.hongxun.design.mytools.IconSourse;
import com.hongxun.design.mytools.MString;
import com.hongxun.design.mytools.MyLog;
import com.hongxun.design.mytools.SetTypeface;
import com.hongxun.design.mytools.ToastShow;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zerdoor_pc on 2016/7/13.
 * 离线地图
 */
public class OfflineMapActivity extends BaseActivity implements View.OnClickListener, MKOfflineMapListener {

    // 默认选中第一个tab
    private int index = 2;
    // fragment管理类
    private FragmentManager fragmentManager;
    //  fragment
    public DownloadmanagementFragment downloadfragment = new DownloadmanagementFragment();
    public CitysFragment citysFragment = new CitysFragment();
    TextView downloadmanagement, listofcities;

    private MKOfflineMap mOffline = null;//离线地图
    public ArrayList<MKOLUpdateElement> localMapList;//已离线数据
    ArrayList<MKOLSearchRecord> records1, records2;
   public List<CitysBean> data;

    public final static int Code_notload = 0;
    public final static int Code_update = 1;
    public final static int Code_load = 2;
    public final static int Code_isloading = 3;
    public final static int Code_continue = 4;
    public final static int Code_child = 5;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_offlinemap);

        inItMap();
        findView();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    /**
     * *******************************************选项卡切换类***************************************
     */
    @Override
    protected void findView() {
        super.findView();
        fragmentManager = getSupportFragmentManager();
        TextView back = (TextView) findViewById(R.id.offlinemap_back);
        SetTypeface.set(back, IconSourse.BACK);

        downloadmanagement = (TextView) findViewById(R.id.downloadmanagement);
        listofcities = (TextView) findViewById(R.id.listofcities);
        downloadmanagement.setOnClickListener(this);
        listofcities.setOnClickListener(this);
        checkChange(downloadfragment, 1);
    }


    /**
     * 点击返回事件*
     */
    public void onback(View v) {
        this.onBackPressed();
    }


    /**
     * 改变现象卡的选中状态
     */
    private void clearStatus() {
        if (index == 1) {
            downloadmanagement.setBackgroundResource(R.drawable.white_left_r6_item);
            downloadmanagement.setTextColor(getResources().getColor(R.color.login_yellow));
            listofcities.setBackgroundResource(R.drawable.yellow_right_r6_item);
            listofcities.setTextColor(getResources().getColor(R.color.white));

        } else if (index == 2) {
            downloadmanagement.setBackgroundResource(R.drawable.yellow_left_r6_item);
            downloadmanagement.setTextColor(getResources().getColor(R.color.white));
            listofcities.setBackgroundResource(R.drawable.white_right_r6_item);
            listofcities.setTextColor(getResources().getColor(R.color.login_yellow));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.downloadmanagement:
                if (index == 1) return;
                checkChange(downloadfragment, 1);
                break;
            case R.id.listofcities:
                if (index == 2) return;
                checkChange(citysFragment, 2);
                break;
        }


    }

    private void checkChange(BaseFragment f, int i) {
        clearStatus();
        if (f == null) {
            f = new BaseFragment();
        }
        replaceFragment(f, i);
        MyLog.L(MString.SUCCESSED + " s_index=" + index);
        index = i;
        MyLog.L(MString.SUCCESSED + " e_index=" + index);

    }

    /**
     * 切换fragment
     *
     * @param newFragment
     */
    BaseFragment currf;

    private void replaceFragment(BaseFragment newFragment, int i) {
        FragmentTransaction transaction = fragmentManager.beginTransaction();
//        if (!newFragment.isAdded()) {
//            transaction.replace(R.id.offlinemap, newFragment);
//            transaction.commit();
//        } else {
//            transaction.show(newFragment);
//        }


        if (!newFragment.isAdded()) {
            transaction.add(R.id.offlinemap, newFragment, i + "");
        } else {
            transaction.show(newFragment);
        }
        if (currf != null && currf != newFragment) {
            transaction.hide(currf);
        }
        transaction.commit();
        currf = newFragment;
    }

    /**********************************************离线地图类****************************************/
    /**
     * 初始化离线地图*
     */
    private void inItMap() {
        mOffline = new MKOfflineMap();
        mOffline.init(this);
        // 获取热闹城市列表
        records1 = mOffline.getHotCityList();
        // 获取所有支持离线地图的城市
        records2 = mOffline.getOfflineCityList();
        // 获取已下过的离线地图信息
        localMapList = mOffline.getAllUpdateInfo();
    }

    public List<CitysBean> getCityData() {
        if (data == null) data = new ArrayList<>();
        if (data.size()>0)data.clear();
        boolean flag = true;
        MyLog.L(MString.SUCCESSED + "data.size1:" + data.size());
        for (MKOLSearchRecord m : records1) {
            CitysBean citysBean = new CitysBean(m.cityID, "热门城市", flag, m.cityName, formatDataSize(m.size), check(m)[0], check(m)[1]);
            if (m.childCities != null && m.childCities.size() > 0) {
                for (MKOLSearchRecord c : m.childCities) {
                    citysBean.setChild(new CitysBean(c.cityID, "热门城市", flag, c.cityName, formatDataSize(c.size), check(c)[0], check(c)[1]));
                }
            }
            data.add(citysBean);
            if (flag) {
                flag = false;
            }
        }
        flag = true;
        MyLog.L(MString.SUCCESSED+"data.size2:"+data.size());
        for (MKOLSearchRecord m : records2) {

            CitysBean citysBean = new CitysBean(m.cityID, "全国", flag, m.cityName, formatDataSize(m.size), check(m)[0], check(m)[1]);
            if (m.childCities != null && m.childCities.size() > 0) {
                for (MKOLSearchRecord c : m.childCities) {
                    citysBean.setChild(new CitysBean(c.cityID, "全国", flag, c.cityName, formatDataSize(c.size), check(c)[0], check(c)[1]));
                }
            }
            data.add(citysBean);
            if (flag) {
                flag = false;
            }
        }
        MyLog.L(MString.SUCCESSED+"data.size3:"+data.size());
        return data;
    }

    /**
     * 计算文件大小*
     */
    public String formatDataSize(int size) {
        String ret = "";
        if (size < (1024 * 1024)) {
            ret = String.format("%dK", size / 1024);
        } else {
            ret = String.format("%.1fM", size / (1024 * 1024.0));
        }
        return ret;
    }

    private int[] check(MKOLSearchRecord m) {
        int flag = Code_notload;
        int code = -1;
        if (localMapList == null || localMapList.size() == 0) return new int[]{flag, code};

        for (MKOLUpdateElement e : localMapList) {
            if (e.cityID == m.cityID) {
                if (e.update) {
                    //可更新
                    flag = Code_update;
                } else {
                    //最新
                    flag = Code_load;
                }
                if (e.ratio >= 0 && e.ratio < 100) {
                    //正在下载
                    flag = Code_isloading;
                    code = e.ratio;
                    if (e.status == 3) {
                        flag = Code_continue;
                    }
                } else {
                    flag = Code_load;
                }
            }
        }
        return new int[]{flag, code};
    }

    @Override
    protected void onDestroy() {
        /**
         * 退出时，销毁离线地图模块
         */
        mOffline.destroy();
        super.onDestroy();
    }

    @Override
    public void onGetOfflineMapState(int type, int state) {
        switch (type) {
            case MKOfflineMap.TYPE_DOWNLOAD_UPDATE: {
                MKOLUpdateElement update = mOffline.getUpdateInfo(state);
                // 处理下载进度更新提示
                if (update != null) {
                    MyLog.L(MString.SUCCESSED + "返回  cityid:" + state + "  cityName:" + update.cityName);
//                    stateView.setText(String.format("%s : %d%%", update.cityName,
//                            update.ratio));
                    updateView(state, update.cityName);
                }
            }
            break;
            case MKOfflineMap.TYPE_NEW_OFFLINE:
                // 有新离线地图安装
                Log.d("OfflineDemo", String.format("add offlinemap num:%d", state));
                break;
            case MKOfflineMap.TYPE_VER_UPDATE:
                // 版本更新提示
                // MKOLUpdateElement e = mOffline.getUpdateInfo(state);

                break;
            default:
                break;
        }

    }

    /**
     * 更新状态显示
     */
    public void updateView(int cityid, String cityName, int... s) {
        localMapList = mOffline.getAllUpdateInfo();
        if (localMapList == null) {
            localMapList = new ArrayList<MKOLUpdateElement>();
        }
        // lAdapter.notifyDataSetChanged();


        if (s.length > 0) {
            citysFragment.Refresh();
            downloadfragment.setAdapter();
        } else if (index == 2) {
            citysFragment.Refresh();
        } else {
            downloadfragment.setAdapter();
        }

    }
    /**
     * 搜索离线需市
     *
     * @param
     */
    public List<CitysBean> search(String city) {
        data.clear();
        ArrayList<MKOLSearchRecord> records = mOffline.searchCity(city);
        if (records == null || records.size() != 1) {
            return data;
        }
        boolean flag = true;
        for (MKOLSearchRecord m : records) {
            CitysBean citysBean = new CitysBean(m.cityID, "搜索结果", flag, m.cityName, formatDataSize(m.size), check(m)[0], check(m)[1]);
            if (m.childCities != null && m.childCities.size() > 0) {
                for (MKOLSearchRecord c : m.childCities) {
                    citysBean.setChild(new CitysBean(c.cityID, "搜索结果", flag, c.cityName, formatDataSize(c.size), check(c)[0], check(c)[1]));
                }
            }
            data.add(citysBean);
            if (flag) {
                flag = false;
            }
        }
        return data;
    }
    /**
     * 开始下载
     *
     * @param
     */
    public void start(int cityid, String cityName) {
        MyLog.L(MString.SUCCESSED + "  cityid:" + cityid + "  cityName:" + cityName);
        mOffline.start(cityid);
        // ToastShow.showShort(this, "开始下载" + cityName + "的离线地图！");
        updateView(cityid, cityName);
    }


    /**
     * 开始更新
     *
     * @param
     */
    public void update(int cityid, String cityName) {
        mOffline.getUpdateInfo(cityid);
        ToastShow.showShort(this, "开始更新" + cityName + "的离线地图！");
        updateView(cityid, cityName);
    }

    /**
     * 暂停下载
     *
     * @param
     */
    public void stop(int cityid, String cityName) {
        mOffline.pause(cityid);
        updateView(cityid, cityName,1);
    }

    /**
     * 删除离线地图
     *
     * @param
     */
    public void remove(int cityid, String cityName) {
        mOffline.remove(cityid);
        updateView(cityid, cityName,1);
    }
}
